package com.xoa.service.party;

import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.footprint.FootPrintMapper;
import com.xoa.dao.party.GridInfoMapper;
import com.xoa.dao.users.UserPrivMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.department.Department;
import com.xoa.model.party.GridInfo;
import com.xoa.model.party.GridInfoUser;
import com.xoa.model.users.Users;
import com.xoa.service.users.UsersService;
import com.xoa.util.AjaxJson;
import com.xoa.util.GetAttachmentListUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.common.wrapper.BaseWrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by gsb on 2017/9/7.
 */
@Service
public class GridInfoService {
    public static final Integer PRCS_FLAG_WILL=1;
    public static final Integer PRCS_FLAG_OVER=2;
    @Autowired
    private GridInfoMapper gridInfoMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private UsersService usersService;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private UserPrivMapper userPrivMapper;
    @Autowired
    private FootPrintMapper footPrintMapper;

    public BaseWrappers gridSettingsList(HttpServletRequest request, Integer griti){
        String sqlType = "xoa"
                + (String) request.getSession().getAttribute("loginDateSouse");
        BaseWrappers baseWrappers = new BaseWrappers();
        List<GridInfo> gridInfos = gridInfoMapper.gridSettingsList();
        if(griti!=null&&griti==1){
                for(int i=gridInfos.size()-1;i>=0;i--){
                    if(gridInfos.get(i)!=null){
                        if(gridInfos.get(i).getGridName()!=null){
                            if(gridInfos.get(i).getGridName().indexOf("网格管理")>-1){

                            }else{
                                if (gridInfos.get(i).getGridName().indexOf("网格") != -1) {
                                    gridInfos.remove(i);
                                }
                            }
                        }
                    }
                }
        }
        for(GridInfo gridInfo:gridInfos){
            if("0".equals(gridInfo.getUpperGrid())){
                gridInfo.setIdentifyingId(0);
            }else{
                gridInfo.setIdentifyingId(1);
            }
            if (!StringUtils.checkNull(gridInfo.getAttachmentName()) && !StringUtils.checkNull(gridInfo.getAttachmentId())) {
                gridInfo.setAttachment(GetAttachmentListUtil.returnAttachment(gridInfo.getAttachmentName(), gridInfo.getAttachmentId(), sqlType, GetAttachmentListUtil.MODULE_grid));
            }
        }
        baseWrappers.setMsg("ok");
        baseWrappers.setStatus(true);
        baseWrappers.setFlag(true);
        baseWrappers.setDatas(gridInfos);
        return baseWrappers;
    }


    public ToJson<GridInfo> gridSettingsTree(HttpServletRequest request, String typeId) {
        String sqlType = "xoa"
                + (String) request.getSession().getAttribute("loginDateSouse");
        ToJson<GridInfo> baseWrappers = new ToJson<GridInfo>();
        List<GridInfo> gridInfos = gridInfoMapper.gridSettingsTree(typeId);
        for ( GridInfo gridInfo:gridInfos){
            if(gridInfo.getGridName()==null || gridInfo.getGridName().equals("")){
                gridInfos.remove(gridInfo);
                continue;
            }
            gridInfo.setDeptId(gridInfo.getGridId().toString());
            gridInfo.setDeptName(gridInfo.getGridName());
            if (!StringUtils.checkNull(gridInfo.getAttachmentName()) && !StringUtils.checkNull(gridInfo.getAttachmentId())) {
                gridInfo.setAttachment(GetAttachmentListUtil.returnAttachment(gridInfo.getAttachmentName(), gridInfo.getAttachmentId(), sqlType, GetAttachmentListUtil.MODULE_grid));
            }

            String baopian=usersMapper.getUsernameByUserId(gridInfo.getBaopianId());
            if(StringUtils.checkNull(baopian)){
                gridInfo.setBaoPianName("");
            }else{
                gridInfo.setBaoPianName(baopian);
            }
            String baoju=usersMapper.getUsernameByUserId(gridInfo.getBaojuId());
            if(StringUtils.checkNull(baoju)){
                gridInfo.setBaoJuName("");
            }else{
                gridInfo.setBaoJuName(baoju);
            }
            String directorName=usersMapper.getUsernameByUserId(gridInfo.getDirectorId());
            if(StringUtils.checkNull(directorName)){
                gridInfo.setDirectorName("");
            }else{
                gridInfo.setDirectorName(directorName);
            }
            String directorIdName=usersService.getUserNameById(gridInfo.getViceDirectorId());
            if(StringUtils.checkNull(directorIdName)){
                gridInfo.setViceDirectorIdName("");
            }else{
                gridInfo.setViceDirectorIdName(directorIdName);
            }
            String gridUserIdName=usersService.getUserNameById(gridInfo.getGridUserId());
            if(StringUtils.checkNull(gridUserIdName)){
                gridInfo.setGridUserIdName("");
            }else{
                gridInfo.setGridUserIdName(gridUserIdName);
            }
        }
        baseWrappers.setMsg("ok");
        baseWrappers.setFlag(0);
        baseWrappers.setObj(gridInfos);
        return baseWrappers;
    }


    public ToJson<GridInfo> gridSettingsTreeList(HttpServletRequest request) {
        String sqlType = "xoa"
                + (String) request.getSession().getAttribute("loginDateSouse");
        ToJson<GridInfo> baseWrappers = new ToJson<GridInfo>();
        List<GridInfo> gridInfos = gridInfoMapper.gridSettingsTreeList();
        for ( GridInfo gridInfo:gridInfos){
            gridInfo.setDeptId(gridInfo.getGridId().toString());
            gridInfo.setDeptName(gridInfo.getGridName());
            if (!StringUtils.checkNull(gridInfo.getAttachmentName()) && !StringUtils.checkNull(gridInfo.getAttachmentId())) {
                gridInfo.setAttachment(GetAttachmentListUtil.returnAttachment(gridInfo.getAttachmentName(), gridInfo.getAttachmentId(), sqlType, GetAttachmentListUtil.MODULE_grid));
            }

            String baopian=usersMapper.getUsernameByUserId(gridInfo.getBaopianId());
            if(StringUtils.checkNull(baopian)){
                gridInfo.setBaoPianName("");
            }else{
                gridInfo.setBaoPianName(baopian);
            }
            String baoju=usersMapper.getUsernameByUserId(gridInfo.getBaojuId());
            if(StringUtils.checkNull(baoju)){
                gridInfo.setBaoJuName("");
            }else{
                gridInfo.setBaoJuName(baoju);
            }
            String directorName=usersMapper.getUsernameByUserId(gridInfo.getDirectorId());
            if(StringUtils.checkNull(directorName)){
                gridInfo.setDirectorName("");
            }else{
                gridInfo.setDirectorName(directorName);
            }
            String directorIdName=usersService.getUserNameById(gridInfo.getViceDirectorId());
            if(StringUtils.checkNull(directorIdName)){
                gridInfo.setViceDirectorIdName("");
            }else{
                gridInfo.setViceDirectorIdName(directorIdName);
            }
            String gridUserIdName=usersService.getUserNameById(gridInfo.getGridUserId());
            if(StringUtils.checkNull(gridUserIdName)){
                gridInfo.setGridUserIdName("");
            }else{
                gridInfo.setGridUserIdName(gridUserIdName);
            }
        }
        baseWrappers.setMsg("ok");
        baseWrappers.setFlag(0);
        baseWrappers.setObj(gridInfos);
        return baseWrappers;
    }

    public ToJson<GridInfo> gridSettingsTrees(HttpServletRequest request, String typeId) {
        Users users= SessionUtils.getSessionInfo(request.getSession(), Users.class,new Users());
        Department departmentOne= departmentMapper.getDeptById(users.getDeptId());
        ToJson<GridInfo> baseWrappers = new ToJson<GridInfo>();
        List<GridInfo> gridInfos = gridInfoMapper.gridSettingsTree(typeId);
        List<GridInfo> gridInfoList=new ArrayList<GridInfo>();
        for ( GridInfo gridInfo:gridInfos){
            gridInfo.setDeptId(gridInfo.getGridId().toString());
            gridInfo.setDeptName(gridInfo.getGridName());

            gridInfoList.add(gridInfo);

        }
        baseWrappers.setMsg("ok");
        baseWrappers.setFlag(0);
        baseWrappers.setObj(gridInfoList);
        return baseWrappers;
    }
    public BaseWrappers insertSelective(GridInfo gridInfo){
        BaseWrappers baseWrappers = new BaseWrappers();
        baseWrappers.setStatus(true);
        gridInfo.setGridId(0);
         int conut= gridInfoMapper.insertSelective(gridInfo);
        if(conut>0){
            baseWrappers.setMsg("ok");

            baseWrappers.setFlag(true);

        }else {
            baseWrappers.setMsg("err");

            baseWrappers.setFlag(false);
        }

        return baseWrappers;
    }

    public BaseWrappers updateByPrimaryKeySelective(GridInfo gridInfo){
        BaseWrappers baseWrappers = new BaseWrappers();
        baseWrappers.setStatus(true);
     int conut= gridInfoMapper.updateByPrimaryKeySelective(gridInfo);
        if(conut>0){
            baseWrappers.setMsg("ok");

            baseWrappers.setFlag(true);

        }else {
            baseWrappers.setMsg("err");

            baseWrappers.setFlag(false);
        }

        return baseWrappers;
    }
    public BaseWrappers deleteByPrimaryKey(Integer gridId){
        BaseWrappers baseWrappers = new BaseWrappers();
        baseWrappers.setStatus(true);

        int conut= gridInfoMapper.deleteByPrimaryKey(gridId);
        if(conut>0){
            //删除改社区下的网格
            int countt=gridInfoMapper.deleteByPrimaryKeyTis(gridId);
            baseWrappers.setMsg("ok");

            baseWrappers.setFlag(true);

        }else {
            baseWrappers.setMsg("err");

            baseWrappers.setFlag(false);
        }

        return baseWrappers;
    }

    public BaseWrapper selectByPrimaryKey(Integer gridId, HttpServletRequest request){
        BaseWrapper baseWrappers = new BaseWrapper();
        baseWrappers.setStatus(true);

       GridInfo gridInfo= gridInfoMapper.selectByPrimaryKey(gridId);
       if(gridInfo!=null){
           String baopian=usersMapper.getUsernameByUserId(gridInfo.getBaopianId().split(",")[0]);
           if(StringUtils.checkNull(baopian)){
               gridInfo.setBaoPianName("");
           }else{
               gridInfo.setBaoPianName(baopian);
           }
           String baoju=usersMapper.getUsernameByUserId(gridInfo.getBaojuId().split(",")[0]);
           if(StringUtils.checkNull(baoju)){
               gridInfo.setBaoJuName("");
           }else{
               gridInfo.setBaoJuName(baoju);
           }
           String directorName=usersMapper.getUsernameByUserId(gridInfo.getDirectorId().split(",")[0]);
           if(StringUtils.checkNull(directorName)){
               gridInfo.setDirectorName("");
           }else{
               gridInfo.setDirectorName(directorName);
           }
           String directorIdName=usersService.getUserNameById(gridInfo.getViceDirectorId());
           if(StringUtils.checkNull(directorIdName)){
               gridInfo.setViceDirectorIdName("");
           }else{
               gridInfo.setViceDirectorIdName(directorIdName);
           }
           String gridUserIdName=usersService.getUserNameById(gridInfo.getGridUserId());
           if(StringUtils.checkNull(gridUserIdName)){
               gridInfo.setGridUserIdName("");
           }else{
               gridInfo.setGridUserIdName(gridUserIdName);
           }
           String sqlType = "xoa"
                   + (String) request.getSession().getAttribute("loginDateSouse");
           if (!StringUtils.checkNull(gridInfo.getAttachmentName()) && !StringUtils.checkNull(gridInfo.getAttachmentId())) {
               gridInfo.setAttachment(GetAttachmentListUtil.returnAttachment(gridInfo.getAttachmentName(), gridInfo.getAttachmentId(), sqlType, GetAttachmentListUtil.MODULE_grid));
           }





           baseWrappers.setMsg("ok");
           baseWrappers.setFlag(true);
           baseWrappers.setData(gridInfo);
       }else{
           baseWrappers.setMsg("err");
           baseWrappers.setFlag(false);
       }

        return baseWrappers;
    }

    public BaseWrappers getUserName(String upperGrid){
        BaseWrappers baseWrappers = new BaseWrappers();
        baseWrappers.setStatus(true);
        try {
            //处理一下字段
            List<GridInfoUser> gridInfoUsers=gridInfoMapper.getUserName(upperGrid);
            baseWrappers.setMsg("ok");
            baseWrappers.setFlag(true);
            baseWrappers.setDatas(gridInfoUsers);
        } catch (Exception e) {
            baseWrappers.setMsg("false");
            baseWrappers.setFlag(false);
            e.printStackTrace();
        }
        return baseWrappers;
    }
    public BaseWrapper updateOrDeleteByPrimaryKey(Integer gridId, Integer updateId, String usId){
        BaseWrapper baseWrappers = new BaseWrapper();
        baseWrappers.setStatus(true);

        GridInfo gridInfo= gridInfoMapper.selectByPrimaryKey(gridId);
        if(gridInfo!=null){
               if(PRCS_FLAG_WILL.equals(updateId)){
                   String userId=gridInfo.getGridUserId();
                   GridInfo gridInfo1=new GridInfo();
                   gridInfo1.setGridId(gridId);
                   if(usersMapper.getUserByUserName(usId)!=null){
                       usId=usersMapper.getUserByUserName(usId).getUserId();
                   }
                   gridInfo1.setGridUserId(userId+usId);
                   int conut= gridInfoMapper.updateByPrimaryKeySelective(gridInfo1);
                   if(conut>0){
                       baseWrappers.setMsg("ok");

                       baseWrappers.setFlag(true);

                   }else {
                       baseWrappers.setMsg("err");

                       baseWrappers.setFlag(false);
                   }
                   return baseWrappers;
              }else if (PRCS_FLAG_OVER.equals(updateId)){
                   GridInfo gridInfo1=new GridInfo();
                   String userId=gridInfo.getGridUserId();
                   String useId=usId+",";
                   userId=userId.replace(useId,"");
                   gridInfo1.setGridId(gridId);
                   if(usersMapper.getUserByUserName(usId)!=null){
                       usId=usersMapper.getUserByUserName(usId).getUserId();
                   }
                   if(userId!=null){
                       userId=userId.replace(usId+",","");
                   }
                   gridInfo1.setGridUserId(userId);
                   int conut= gridInfoMapper.updateByPrimaryKeySelective(gridInfo1);
                   if(conut>0){
                       baseWrappers.setMsg("ok");

                       baseWrappers.setFlag(true);

                   }else {
                       baseWrappers.setMsg("err");

                       baseWrappers.setFlag(false);
                   }
                   return baseWrappers;
               }
        }
        return baseWrappers;
    }



    public BaseWrappers selectByUid(HttpServletRequest request){
        BaseWrappers wrappers=new BaseWrappers();
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class,new Users());
         List<GridInfo> gridInfos=gridInfoMapper.selectByUid( users.getUid().toString());
        List<GridInfo> gridInfoList=new ArrayList<GridInfo>();
        for (int i = 0; i < gridInfos.size() - 1; i++) {
            for (int j = gridInfos.size() - 1; j > i; j--) {
                if (gridInfos.get(j).getViceDirectorId().equals(gridInfos.get(i).getViceDirectorId())) {
                    gridInfos.remove(j);
                }
            }
        }
        for(GridInfo gridInfo:gridInfos){

         String directorIdName=usersService.getUserNameById(gridInfo.getViceDirectorId());
            String[] strings=directorIdName.split(",");
            String[] stringss=gridInfo.getViceDirectorId().split(",");
         for(int i=0;i<strings.length;i++){
             GridInfo gridInfo1=new GridInfo();
            gridInfo1.setUserId(stringss[i]);
            gridInfo1.setViceDirectorIdName(strings[i]);
             if(StringUtils.checkNull(gridInfo1.getDirectorName())&& StringUtils.checkNull(gridInfo1.getUserId())){
             }else{
                 gridInfoList.add(gridInfo1);
             }
         }

         }

        wrappers.setDatas(gridInfoList);
        wrappers.setStatus(true);
        wrappers.setFlag(true);
        wrappers.setMsg("ok");
        return wrappers;
    }

    public BaseWrapper queryByUidMessage(Integer uid){
        BaseWrapper wrappers=new BaseWrapper();

        Users users=usersMapper.selectUserByUId(uid);
        StringBuffer stringBuffer=new StringBuffer();
        List<GridInfo> gridInfos=gridInfoMapper.selectByUid(users.getUid().toString());
        for(GridInfo gridInfo:gridInfos){
           // GridInfo infoName = gridInfoMapper.selectByPrimaryKey(Integer.parseInt(gridInfo.getUpperGrid()));
//          if(infoName!=null){
//              stringBuffer.append(infoName.getGridName());
//          }else {
              stringBuffer.append(gridInfo.getGridName());

      //    }

        }

       // users.setInfoName(stringBuffer.toString());
      //  users.setFoot(footPrintMapper.queryByUId(users.getUid()).get(0));
        wrappers.setData(users);
        wrappers.setStatus(true);
        wrappers.setFlag(true);
        wrappers.setMsg("ok");
        return wrappers;
    }

    public AjaxJson selectGrid(Users users){
        AjaxJson ajaxJson = new AjaxJson();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<GridInfo> gridInfos=gridInfoMapper.selectByUid(users.getUid().toString());
            if (gridInfos==null||gridInfos.size()==0){
                ajaxJson.setMsg("该用户不是网格员！");
                ajaxJson.setFlag(false);
                ajaxJson.setObj(map);
                return ajaxJson;
            }
            GridInfo gridInfo = gridInfos.get(0);
            if(gridInfo.getGridName().contains("社区")){
                map.put("gridName2",gridInfo.getGridName());
                map.put("gridId2",gridInfo.getGridId());
                if(gridInfos.size()>1){
                    map.put("gridName1",gridInfos.get(1).getGridName());
                    map.put("gridId1",gridInfos.get(1).getGridId());
                }
            }else {
                map.put("gridName1",gridInfo.getGridName());
                map.put("gridId1",gridInfo.getGridId());
            }
            if ("0".equals(gridInfo.getUpperGrid())){
            }else {
                GridInfo gridInfo1= gridInfoMapper.selectByPrimaryKey(Integer.parseInt(gridInfo.getUpperGrid()));
                if(gridInfo1!=null){
                    map.put("gridName2",gridInfo1.getGridName());
                    map.put("gridId2",gridInfo1.getGridId());
                }
            }
            ajaxJson.setMsg("OK");
            ajaxJson.setFlag(true);
            ajaxJson.setObj(map);
        }catch (Exception e){
            e.printStackTrace();
            ajaxJson.setMsg("false");
            ajaxJson.setFlag(false);
        }
      return ajaxJson;
    }


}